package handler

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"

	"admin-nexus-backend/internal/dto"
	"admin-nexus-backend/internal/service"
	"admin-nexus-backend/pkg/response"
)

// CityHandler 城市管理控制器
type CityHandler struct {
	cityService *service.CityService
}

// NewCityHandler 创建城市控制器实例
func NewCityHandler(cityService *service.CityService) *CityHandler {
	return &CityHandler{cityService: cityService}
}

// GetCityList 获取城市列表
// @Summary 获取城市列表
// @Description 分页获取城市列表，支持条件筛选
// @Tags 城市管理
// @Accept json
// @Produce json
// @Param page query int false "页码" default(1)
// @Param page_size query int false "每页数量" default(10)
// @Param name query string false "城市名称"
// @Param province_name query string false "所属省份名称"
// @Param status query int false "状态 0-禁用 1-启用"
// @Param sort_by query string false "排序字段"
// @Param order query string false "排序方式 asc/desc"
// @Success 200 {object} response.Response{data=dto.PageResult{list=[]dto.CityResponse}} "成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 401 {object} response.Response "未授权"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/cities [get]
func (h *CityHandler) GetCityList(c *gin.Context) {
	var req dto.CityListRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ErrorWithCode(c, http.StatusBadRequest, "请求参数错误: "+err.Error())
		return
	}

	// 设置默认值
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 || req.PageSize > 100 {
		req.PageSize = 10
	}

	result, err := h.cityService.GetCityList(&req)
	if err != nil {
		response.ErrorWithCode(c, http.StatusInternalServerError, "获取城市列表失败: "+err.Error())
		return
	}

	response.SuccessWithData(c, result)
}

// GetCityByID 根据ID获取城市信息
// @Summary 根据ID获取城市信息
// @Description 根据城市ID获取城市详细信息
// @Tags 城市管理
// @Accept json
// @Produce json
// @Param id path int true "城市ID"
// @Success 200 {object} response.Response{data=dto.CityResponse} "成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 404 {object} response.Response "城市不存在"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/cities/{id} [get]
func (h *CityHandler) GetCityByID(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.ErrorWithCode(c, http.StatusBadRequest, "无效的城市ID")
		return
	}

	city, err := h.cityService.GetCityByID(uint(id))
	if err != nil {
		if err.Error() == "城市不存在" {
			response.ErrorWithCode(c, http.StatusNotFound, err.Error())
		} else {
			response.ErrorWithCode(c, http.StatusInternalServerError, "获取城市信息失败: "+err.Error())
		}
		return
	}

	response.SuccessWithData(c, city)
}

// CreateCity 创建城市
// @Summary 创建城市
// @Description 创建新的城市信息
// @Tags 城市管理
// @Accept json
// @Produce json
// @Param data body dto.CityCreateRequest true "城市信息"
// @Success 200 {object} response.Response "成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 409 {object} response.Response "城市名称已存在"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/cities [post]
func (h *CityHandler) CreateCity(c *gin.Context) {
	var req dto.CityCreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.ErrorWithCode(c, http.StatusBadRequest, "请求参数错误: "+err.Error())
		return
	}

	err := h.cityService.CreateCity(&req)
	if err != nil {
		if err.Error() == "城市名称已存在" {
			response.ErrorWithCode(c, http.StatusConflict, err.Error())
		} else {
			response.ErrorWithCode(c, http.StatusInternalServerError, "创建城市失败: "+err.Error())
		}
		return
	}

	response.SuccessWithMessage(c, "创建城市成功")
}

// UpdateCity 更新城市
// @Summary 更新城市
// @Description 更新城市信息
// @Tags 城市管理
// @Accept json
// @Produce json
// @Param id path int true "城市ID"
// @Param data body dto.CityUpdateRequest true "城市信息"
// @Success 200 {object} response.Response "成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 404 {object} response.Response "城市不存在"
// @Failure 409 {object} response.Response "城市名称已存在"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/cities/{id} [put]
func (h *CityHandler) UpdateCity(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.ErrorWithCode(c, http.StatusBadRequest, "无效的城市ID")
		return
	}

	var req dto.CityUpdateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.ErrorWithCode(c, http.StatusBadRequest, "请求参数错误: "+err.Error())
		return
	}

	err = h.cityService.UpdateCity(uint(id), &req)
	if err != nil {
		switch err.Error() {
		case "城市不存在":
			response.ErrorWithCode(c, http.StatusNotFound, err.Error())
		case "城市名称已存在":
			response.ErrorWithCode(c, http.StatusConflict, err.Error())
		default:
			response.ErrorWithCode(c, http.StatusInternalServerError, "更新城市失败: "+err.Error())
		}
		return
	}

	response.SuccessWithMessage(c, "更新城市成功")
}

// DeleteCity 删除城市
// @Summary 删除城市
// @Description 删除指定城市
// @Tags 城市管理
// @Accept json
// @Produce json
// @Param id path int true "城市ID"
// @Success 200 {object} response.Response "成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 404 {object} response.Response "城市不存在"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/cities/{id} [delete]
func (h *CityHandler) DeleteCity(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.ErrorWithCode(c, http.StatusBadRequest, "无效的城市ID")
		return
	}

	err = h.cityService.DeleteCity(uint(id))
	if err != nil {
		if err.Error() == "城市不存在" {
			response.ErrorWithCode(c, http.StatusNotFound, err.Error())
		} else {
			response.ErrorWithCode(c, http.StatusInternalServerError, "删除城市失败: "+err.Error())
		}
		return
	}

	response.SuccessWithMessage(c, "删除城市成功")
}

// BatchDeleteCity 批量删除城市
// @Summary 批量删除城市
// @Description 批量删除指定城市
// @Tags 城市管理
// @Accept json
// @Produce json
// @Param data body dto.CityBatchDeleteRequest true "城市ID列表"
// @Success 200 {object} response.Response "成功"
// @Failure 400 {object} response.Response "请求参数错误"
// @Failure 404 {object} response.Response "部分城市不存在"
// @Failure 500 {object} response.Response "服务器内部错误"
// @Router /api/v1/cities/batch-delete [post]
func (h *CityHandler) BatchDeleteCity(c *gin.Context) {
	var req dto.CityBatchDeleteRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.ErrorWithCode(c, http.StatusBadRequest, "请求参数错误: "+err.Error())
		return
	}

	err := h.cityService.BatchDeleteCity(&req)
	if err != nil {
		if err.Error() == "部分城市不存在" {
			response.ErrorWithCode(c, http.StatusNotFound, err.Error())
		} else {
			response.ErrorWithCode(c, http.StatusInternalServerError, "批量删除城市失败: "+err.Error())
		}
		return
	}

	response.SuccessWithMessage(c, "批量删除城市成功")
}
